package com.health.viewscontrols.medical.device.bg;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.blankj.utilcode.util.ToastUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.clj.fastble.utils.HexUtil;
import com.health.viewscontrols.medical.base.BaseDeviceActivity;
import com.inuker.bluetooth.library.Contast;
import com.inuker.bluetooth.library.ZBleManager;
import com.inuker.bluetooth.library.interFace.IBleConnectStatusListener;
import com.inuker.bluetooth.library.interFace.IBleIndicateListener;
import com.inuker.bluetooth.library.interFace.IBleWriteListener;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.nova.health.ble.callback.OnDeviceConnectChangedListener;
import com.novabluetooth.data.DeviceShowSaveData;
import com.novabluetooth.views.twj.StringUtil;
import com.novabluetooth.views.twj.ZHexUtil;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.UUID;

/**
 * 三诺血糖仪
 */
public class BGAALActivity extends BaseDeviceActivity {

    private ZBleManager mBleManager;
    boolean first = true;//只发一次信息包
    private int agreement_type;//1:1.0协议;2:2.0或3.0协议

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (first) {
                switch (msg.what) {
                    case 0:
                        byte[] data_05 = ZHexUtil.hexStringToBytes(getSendHex());
                        write(deviceEnum.getMac(), data_05);
                        break;
                    case 1:
                        byte[] data_00 = ZHexUtil.hexStringToBytes(getSendHex(0));
                        write(deviceEnum.getMac(), data_00);
                        break;
                    default:
                        break;
                }
                first = false;
            }
        }
    };

    @Override
    public void doBusiness() {
        tv_operation_tips.setText(com.nova.health.ble.R.string.bg_AAL);

        mBleManager = ZBleManager.getInstance();
        mBleManager.initBle(this);

        BleManager.getInstance().init(getApplication());

        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                .setDeviceMac(deviceEnum.getMac())
                .setScanTimeOut(10000)              // 扫描超时时间，可选，默认10秒；小于等于0表示不限制扫描时间
                .build();
        BleManager.getInstance().initScanRule(scanRuleConfig);
    }

    @Override
    public void startDevice() {
        showProgressDialog("开始连接设备");
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
            }

            @Override
            public void onLeScan(BleDevice bleDevice) {
                super.onLeScan(bleDevice);
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                if (bleDevice != null && bleDevice.getMac() != null && deviceEnum.getMac().equals(bleDevice.getMac())) {
                    connDevice();
                }
            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {

            }
        });
    }

    @Override
    public void update(String hexStr) {

    }

    @Override
    public void disconnectDevice() {
        try {
            ZBleManager.getInstance().disConnectDevice(deviceEnum.getMac());
            ZBleManager.getInstance().destroy(deviceEnum.getMac());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getSendHex(int sendPack) {
        SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd-HH-mm-ss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        String content = sdf.format(new Date());
        String[] arrTime = content.split("-");
        if (arrTime.length == 6) {
            int index0 = 90;
            int index1 = 10;
            int index2 = sendPack;//packet category
            int index3 = Integer.parseInt(arrTime[0]);//Year
            int index4 = Integer.parseInt(arrTime[1]);//Month
            int index5 = Integer.parseInt(arrTime[2]);//Day
            int index6 = Integer.parseInt(arrTime[3]);//Hour
            int index7 = Integer.parseInt(arrTime[4]);//Minute
            int index8 = Integer.parseInt(arrTime[5]);//Second
            int index9 = index0 + index1 + index2 + index3 + index4 + index5 + index6 + index7 + index8 + 2;
            if (index9 > 255) {
                index9 = index9 % 255;
            }
            byte[] data = new byte[]{(byte) index0, (byte) index1, (byte) index2, (byte) index3,
                    (byte) index4, (byte) index5, (byte) index6, (byte) index7, (byte) index8};

            String hexSend = ZHexUtil.encodeHexStr(data);
            String hexIndex9 = ZHexUtil.encodeHexStr(new byte[]{(byte) index9});
            int len = hexIndex9.length();
            String i9 = hexIndex9.substring(len - 2, len);
            return String.format("%s%s", hexSend, i9).toUpperCase();
        }
        return "";
    }

    /**
     * "1.0"协议的"05"应答包
     *
     * @return
     */
    public static String getSendHex() {
        //5AH	0BH	05H	0EH	0BH	08H	0CH	12H	A9H	00H	00H

        int index0 = 90;//5A->90起始码
        int index1 = 11;//0B->11包长
        int index2 = 5;//05 包类别
        int index3 = 14;//年
        int index4 = 11;//月
        int index5 = 8;//日
        int index6 = 12;//时
        int index7 = 18;//分
        int index8 = 169;//8,9,10为Check_sum
        int index9 = 0;//
        int index10 = 0;//

        byte[] data = new byte[]{(byte) index0, (byte) index1, (byte) index2, (byte) index3,
                (byte) index4, (byte) index5, (byte) index6, (byte) index7, (byte) index8, (byte) index9, (byte) index10};

        String hexSend = ZHexUtil.encodeHexStr(data);
        return hexSend.toUpperCase();
    }

    private void connDevice() {
        mBleManager.connect(deviceEnum.getMac(), new IBleConnectStatusListener() {
            @Override
            public void onStartConnect() {
                blueToothState.setText("开始连接蓝牙");
            }

            @Override
            public void onConnectFail() {
                blueToothState.setText("连接蓝牙失败");
            }

            @Override
            public void onConnectSuccess(int code, BleGattProfile data, String mac) {
                blueToothState.setText("连接蓝牙成功");
                showProgressDialog("等待接收血糖数据");
                indicate();
            }

            @Override
            public void onDisConnected(String mac) {
                blueToothState.setText("蓝牙连接已取消");
            }
        });
    }

    @SuppressLint("CheckResult")
    private void write(final String mac, final byte[] data) {
        mBleManager.write(mac, Contast.GATT_SERVICE_PRIMARY,
                Contast.CHARACTERISTIC_WRITEABLE, data, new IBleWriteListener() {
                    @Override
                    public void onWriteSuccess() {
                        Log.e("zdw成功", Arrays.toString(data));
                        if (data[2] == 0)
                            handler.sendEmptyMessageDelayed(0, 2000);
                        else
                            handler.sendEmptyMessageDelayed(1, 2000);
                    }

                    @Override
                    public void onWriteFailure(int code) {
                        Log.e("zdw失败", Arrays.toString(data));
//                        showMessage("未收到测量数据，请尝试重启设备并刷新页面");
                    }
                });
    }

    private void indicate() {
        mBleManager.indicate(deviceEnum.getMac(), Contast.GATT_SERVICE_PRIMARY,
                Contast.CHARACTERISTIC_READABLE, new IBleIndicateListener() {
                    @Override
                    public void onIndicateSuccess() {
                        try {
                            Thread.sleep(500L);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        byte[] data_00 = ZHexUtil.hexStringToBytes(getSendHex(0));
//                        byte[] data_00 = ZHexUtil.hexStringToBytes(TwjConstans.getSendHex(1));
                        write(deviceEnum.getMac(), data_00);
                    }

                    @Override
                    public void onIndicateFailure(int code) {
                        Log.e(TAG, "onIndicateFailure: " + code );
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        Log.e(TAG, "血糖仪返回: " + Arrays.toString(data) );
                        getVersion(data);
                        getBleInfo(data);
                        showContent(data);
                    }
                });
    }

    /**
     * 信息包
     * <p>
     * "00" package
     * Get the bluetooth device protocol version
     */
    private void getVersion(byte[] data) {
        if (null == data) return;
        int length = data.length;
        byte index0 = data[0];
        if (index0 != 85) return;
        if (data.length < 2) return;
        byte index2 = data[2];
        if (index2 == 0) {
            first = false;
            if (length == 15 || length == 18) {
                agreement_type = 2;
            } else {
                agreement_type = 1;
                byte[] data_05 = ZHexUtil.hexStringToBytes(getSendHex());
                write(deviceEnum.getMac(), data_05);
            }
        }
    }

    /**
     * @param data "3.0" protocol "00" package length:18
     * @param data "2.0" protocol "00" package length:15
     */
    private void getBleInfo(byte[] data) {
        if (null == data) return;
        if (data.length != 18 && data.length != 15) return;
        byte index0 = data[0];
        if (index0 != 85) return;
        byte index2 = data[2];
        if (index2 != 0) return;
        //sn
        byte[] snArray = new byte[9];
        System.arraycopy(data, 8, snArray, 0, 9);
        byte index4 = data[4];
    }

    private void showContent(byte[] data) {
        if (null == data) return;
        byte index0 = data[0];
        if (index0 != 85) return;
        byte index2 = data[2];
        if (index2 == 3) {//Device upload results
//            if (!flag) return;
            byte index3 = data[3];//Year
            byte index4 = data[4];//Month
            byte index5 = data[5];//Day
            byte index6 = data[6];//Hour
            byte index7 = data[7];//Minute
            byte[] valueArr = {data[10], data[9]};
            String strValue = ZHexUtil.encodeHexStr(valueArr);//10+9 Convert to decimal
            int value = Integer.valueOf(strValue, 16);
            String valueStr = StringUtil.formatTo1((double) value / 18);
//            flag = false;
            saveMaiboboData(valueStr);
        } else if (index2 == 5) {
        }
    }

    private void saveMaiboboData(String bg) {
        try {
            cancelProgressDialog();
            //收缩压、舒张压、心率
            DeviceShowSaveData.getDataShow(bg + "","Bioland-BGM");
            DeviceShowSaveData.saveXuetang(bg + "");

            tv_state.setText("获取测量结果成功");
            tv_result.setText("血糖值： " + bg  + "mmol/L");
            ToastUtils.showShort("获取测量结果成功");

            ZBleManager.getInstance().disConnectDevice(deviceEnum.getMac());
            ZBleManager.getInstance().destroy(deviceEnum.getMac());
            cancelProgressDialog();
        } catch (Exception e) {
            Log.e(TAG, "报异常了: " + e.toString());
        }
    }

}
